import {
  get,
  common,
  getRefresh
} from '../../../api/api'

const SET_AUTH_LOADING = 'set_auth_loading'

const state = {
  loading: false,
  userInfo: {
    role: null,
    info: null,
  },
  captcha_img: '',
  islogin: 0,
  username: '',
  person_info: {},
}

const getters = {
  getAuthLoading: state => state.loading,
  getRole: state => state.userInfo.role,
  getUsername: state => state.username,
}

const actions = {
  //自动得到用户信息
  async userInfo({
    state,
    dispatch
  }, this_p) {
    if (state.userInfo.role !== null) return;
    await get('/auth/auto-login').then(resdata => {
      let data = resdata.data;
      let self = /*async*/ function () {
        /*await*/ get('/auth/refresh').then(data => {
          if (data.code != 0) {
            localStorage.removeItem('token');
            this_p.$router.push({
              path: '/home'
            });
          } else {
            localStorage.setItem('token', data.data.token);
            dispatch('userInfo', this_p);
          }
        });
      }.bind(this_p);
      let error = function () {
        this_p.$message({
          message: resdata.msg,
          type: 'error'
        });
        localStorage.removeItem('token');
        this_p.$router.push({
          path: '/home'
        });
        dispatch('captcha');
      };
      let success = function () {
        state.userInfo = {
          role: data.role,
          info: data.info
        };
        sessionStorage.setItem("person_info", JSON.stringify(data.info));
        sessionStorage.setItem("islogin", true);
        sessionStorage.setItem("loginName", data.loginName);
        state.person_info = data.info;
        state.loginName = data.loginName;
      };
      common(self)(error)(success)(resdata);
    });
  },
  //得到图片验证码
  captcha({
    state
  }) {
    get('/auth/captcha-img').then(resdata => {
      let data = resdata.data;
      let error = function () {
        this.$message({
          message: '服务器异常，请稍候再试',
          type: 'error'
        });
      };
      let success = function () {
        state.captcha_img = data.url;
      };
      common()(error)(success)(resdata);
    });
  },
}

const mutations = {
  [SET_AUTH_LOADING](state, bool) {
    state.loading = bool;
  },
  islogin(state, val) {
    state.islogin = val;
  }
}

export default {
  state,
  getters,
  actions,
  mutations
}
